package com.example.jpetstoreclient.controller;

import com.example.jpetstoreclient.common.CommonResponse;
import com.example.jpetstoreclient.domain.History;
import com.example.jpetstoreclient.service.HistoryService;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Validated
@RestController
@RequestMapping("/history")
public class HistoryController {
    @Autowired
    private HistoryService historyService;

    @GetMapping("/{id}")
    public CommonResponse<List<History>> get(@PathVariable @NotNull(message = "用户ID不能为空") int id){
        return historyService.getHistoryByUserId(id);
    }

    @PostMapping("/save")
    public CommonResponse<History> save(@RequestBody History history){
        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        history.setTime(sbf.format(new Date()));
        return historyService.addHistory(history);
    }

    @DeleteMapping("/delete/{id}")
    public CommonResponse<History> delete(@PathVariable @NotNull(message = "历史记录ID不能为空") int id){
        if (historyService.removeById(id)){
            return CommonResponse.createForSuccessMessage("删除成功");
        }
        return CommonResponse.createForError("删除失败");
    }
}
